package com.sh.common.encoding;

import java.io.IOException;
import java.util.Iterator;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class EncodingFilter implements Filter {
	
	private FilterConfig config = null;
	private String targetEncoding = null;
	
	/**
	 * 初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
		this.targetEncoding = config.getInitParameter("encoding");
	}
	
	/**
	 * 过滤编码
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		// get方式提交的处理
		if (req.getMethod().equalsIgnoreCase("get")) {
			this.encoding(req);
		}
		// post方式提交的处理
		request.setCharacterEncoding(this.targetEncoding);
		response.setCharacterEncoding(this.targetEncoding);
		chain.doFilter(request, response);
	}
	
	/**
	 * 读取参数列表，修正了中文问题。
	 */
	public void encoding(HttpServletRequest request) {
		Iterator iter = request.getParameterMap().values().iterator();
		while (iter.hasNext()) {
			String[] parames = (String[]) iter.next();
			for (int i = 0; i < parames.length; i++) {
				try {
					parames[i] = new String(parames[i].getBytes("iso8859-1"),this.targetEncoding);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 销毁
	 */
	public void destroy() {
		this.config = null;
		this.targetEncoding = null;
	}
}